<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center" style="display:flex; justify-content:space-between;">
                        <div style="display: flex; align-items: center;">
                            <div>
                                {{ route.query.readonly ? '查看保养记录' : route.query.id ? '编辑保养记录' : '新增保养记录' }}
                            </div>
                            <el-tag v-if="route.query.code" :type="tagType" style="margin-left: 10px;">{{ route.query.code
                            }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div>
                        <el-button v-if="!readonly" class="button" type="primary" @click="handleSubmit"> 保 存
                        </el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form ref="recordsRef" :model="form" :rules="rules" :disabled="readonly" label-width="130px">

                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="计划保养时间" prop="startTime">
                                        <el-date-picker v-model="form.startTime" style="width: 100%;"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                                            @change="comparisonTime" placeholder="请选择计划保养时间" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="下发部门" prop="deptCode">
                                        <el-tree-select style="width:300px" v-model="form.deptCode" :data="deptOptions"
                                            :props="{ value: 'id', label: 'label', children: 'children' }"
                                            @node-click="handleChange" value-key="id" check-strictly />
                                    </el-form-item>
                                </el-col>
                            </el-row>


                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="完成情况">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"
                                            style="width: 100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">关联设备</span>
                    </template>
                    <div>
                        <el-button style="margin-bottom: 5px;" v-if="mesMachineCarereationList.length == 0" type="primary"
                            size="small" plain icon="Plus" @click="handleChoice">选择 设备/机台</el-button>
                        <el-table :data="mesMachineCarereationList" border style="width: 100%">
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="machineNo" label="设备编码" align="center" />
                            <el-table-column prop="machineName" label="设备名称" align="center" />
                            <el-table-column fixed="right" label="操作" align="center">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" @click="handleDel(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <machineDialog :visible="visibleMachine" @changeUpdate="changeUserData" @cancel="() => { visibleMachine = false }">
        </machineDialog>
    </div>
</template>
<script setup>
import { computed } from 'vue';
import machineDialog from '@/components/SearchWorkBench'
import useTagsViewStore from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()
import { getCaredetail, addCaredetail, updateCaredetail } from '@/api/maintenance/records.js'

import { deptTreeSelect } from "@/api/system/user";
import { ElMessage, ElMessageBox } from 'element-plus'
const router = useRouter();
const route = useRoute();
const activeNames = ['1']
const recordsRef = ref(null)
const visibleMachine = ref(false)


const mesMachineCarereationList = ref([])
const total = ref(0)
const readonly = ref(false)
const deptOptions = ref(undefined);
const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
    },
    form: {},
    rules: {
        startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" },],
        endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" },],
        planMultiple: [{ required: true, message: "生成日期不能为空", trigger: "blur" }],
        deptCode: [{ required: true, message: "下发部门不能为空", trigger: "blur" }],
    },
});
const { form, rules, queryParams, } = toRefs(data);
const tagType = computed(() => {
    return route.query.status == 0 ? '' : route.query.status == 1 ? 'info' : route.query.status == 2 ? 'success' : route.query.status == 3 ? '' : route.query.status == 4 ? 'danger' : 'warning';
});
readonly.value = route.query.readonly
if (route.query.id) {
    getCaredetail(route.query.id).then(response => {
        form.value = response.data
        form.value.deptCode = Number(form.value.deptCode)

        mesMachineCarereationList.value.push({ machineNo: response.data.machineNo, machineName: response.data.machineName })

    })
} else {
    form.value = {}
}
/** 查询部门下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        deptOptions.value = response.data;
    });
};
const handleChange = (data) => {
    console.log('data', data)
    form.value.deptName = data.label;
}
const comparisonTime = (data) => {
    const providedDate = new Date(data); // 将提供的日期字符串转换为 Date 对象
    const currentDate = new Date(); // 获取当前日期
    // 提取日期部分，不考虑时间
    const providedDateWithoutTime = new Date(providedDate.getFullYear(), providedDate.getMonth(), providedDate.getDate());
    const currentDateWithoutTime = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
    if (providedDateWithoutTime < currentDateWithoutTime) {
        form.value.startTime = undefined
        form.value.endTime = undefined
        return ElMessage({
            message: '日期不能小于当前日',
            type: 'warning',
        });
    }
}
const handleChoice = () => {
    visibleMachine.value = true
}
const changeUserData = (row) => {
    console.log('row', row)
    mesMachineCarereationList.value.push(row)
    visibleMachine.value = false
}
const handleDel = (row) => {
    console.log('row', row)
    const index = mesMachineCarereationList.value.indexOf(row);
    if (index !== -1) {
        mesMachineCarereationList.value.splice(index, 1);
    }
}
const handleQuery = () => {


}
const resetQuery = () => {

}
//保存

const handleSubmit = () => {
    if (!mesMachineCarereationList.value.length && mesMachineCarereationList.value.length === 0) {
        return ElMessage({
            message: '请至少选择一个设备',
            type: 'warning',
        });
    }
    recordsRef.value.validate((valid) => {
        if (valid) {
            const formData = form.value;
            formData.machineNo = mesMachineCarereationList.value[0].machineNo;
            if (formData.id) {
                updateCaredetail(formData).then(response => {
                    if (response.code === 200) {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        goBack();
                    }
                })
            } else {
                formData.status = 0;
                addCaredetail(formData).then(response => {
                    if (response.code === 200) {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        goBack();
                    }
                })
            }
        }
    });
};

//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.back()
}
getDeptTree();
</script>

<style lang="scss" scoped></style>